﻿using System.Linq;
using Enyim.Caching;
using System.Web.Mvc;
using Web.OAuth.Client;
using SilenthinkContract;
using Web.OAuth.Client.Impl;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;

namespace Web.Areas.Passport.Controllers
{
    public class ExternalController : Controller
    {
        protected IPassportService PassportService { get; private set; }
        protected static IMemcachedClient MemcachedClient { get; private set; }
        public ExternalController(IPassportService passportService, IMemcachedClient memcachedClient)
        {
            PassportService = passportService;
            MemcachedClient = memcachedClient;
        }

        public ActionResult Index(string param)
        {
            var client = GetOAuthClient(param);

            if (client != null)
            {
                var url = client.GetLoginUri();
                return Redirect(url);
            }
            return Redirect("/");
        }

        public ActionResult Auth(string param)
        {
            var client = GetOAuthClient(param);
            if (client != null)
            {
                var user = client.GetUserInfo(Request.QueryString);
                if (user != null)
                {
                    //var identity = new SilenthinkIdentity(user.Id, user.NickName, user.Role, string.Empty);
                    //SetAuthCookie(user.Name, remember, identity);

                    return Content(user.Id);
                }
            }

            return Redirect("/");
        }

        private IOAuthClient GetOAuthClient(string name)
        {
            IOAuthClient client = null;
            var configs = MemcachedClient.Put(CacheKey.Passport.OAuthConfigs,
                                              () => PassportService.GetOAuthConfigs(true));
            var config = configs.FirstOrDefault(o => o.ClientName.ToLower() == name.ToLower());

            if (config != null && config.ClientName.ToLower() == "qq")
            {
                client = new QqClient(config);
            }
            else if (config != null && config.ClientName.ToLower() == "sina")
            {
                client = new SinaClient(config);
            }
            return client;
        }
    }

}
